<template>
  <div class="app-container">
    <div class="tableBar" style="margin: 10px 55px ">
      <el-form :inline="true" :model="searchObj" class="demo-form-inline">
        <el-form-item label="关键字搜索" style="margin: 0 10px">
          <el-input
            v-model="searchObj.searchText"
            style="width: 210px"
            placeholder="请输入关键字"
            clearable
            @clear="getLostList"
            @keyup.enter.native="getLostList"
          ></el-input>
        </el-form-item>
        <el-form-item label="找回状态" style="margin: 0 10px">
          <el-select
            v-model="searchObj.status"
            style="width: 155px"
            placeholder="请选择"
            clearable
            @clear="getLostList"
            @keyup.enter.native="getLostList">
            <el-option label="已找回" value="1"></el-option>
            <el-option label="未找回" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" :model="searchObj">
        <el-form-item prop="date2" label="发布时间" style="margin: 0 10px">
          <el-date-picker
            v-model="searchObj.beginTime"
            style="width: 190px"
            type="date"
            placeholder="选择发布时间"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            clearable
            @change="changeBeginDate">
          </el-date-picker>
          <span> - </span>
          <el-date-picker
            v-model="searchObj.endTime"
            style="width: 190px"
            type="date"
            placeholder="选择发布日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            clearable
            @change="changeEndDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="margin: 0 10px">
          <el-button type="primary" @click="getLostList">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </el-form-item>

        <el-button plain style="float: right;margin-right: 20px;margin-top: 20px" @click="showAddDialog">新增分类
        </el-button>
      </el-form>

    </div>

    <el-table
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="tableData"
      style="width: 90%;margin:20px auto;"
      row-key="id"
      border>
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column type="expand" width="20">
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="标题">
              <span v-html="props.row.title">{{ props.row.title }}</span>
            </el-form-item>
            <el-form-item label="发布人头像">
              <img :src="props.row.avatar" width="100">
            </el-form-item>
            <el-form-item label="发布人">
              <span v-html="props.row.nickname">{{ props.row.nickname }}</span>
            </el-form-item>
            <el-form-item label="发布人id">
              <span>{{ props.row.userId }}</span>
            </el-form-item>
            <el-form-item label="发布时间">
              <span>{{ props.row.createTime }}</span>
            </el-form-item>

          </el-form>
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="描述">
              <span v-html="props.row.descrip">{{ props.row.descrip }}</span>
            </el-form-item>
          </el-form>

        </template>
      </el-table-column>
      <el-table-column
        prop="id"
        label="编号"
        sortable
        align="center">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        align="center">
        <template slot-scope="scope">
          <span v-html="scope.row.title"></span>
        </template>
      </el-table-column>
      <el-table-column
        label="失物照片"
        width="200"
        align="center">
        <template slot-scope="scope">
          <img :src="scope.row.picture" min-width="70" height="70"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="80"
        align="center">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === 0 ? 'warning' : 'success'"
            disable-transitions>
            {{ scope.row.status === 0 ? '未找回' : '已找回' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 0"
            @click="handleFound(scope.row.id)"
            icon="el-icon-check"
            circle
            style="margin:  1px 0 0  10px "
            size="mini"
            type="success">
          </el-button>
          <el-button
            @click="handleUpdate(scope.row.id)"
            icon="el-icon-edit"
            circle
            style="margin:  1px 0 0  10px "
            size="mini"
            type="primary">
          </el-button>
          <el-button
            icon="el-icon-delete"
            circle
            style="margin: 1px 0 1px 10px "
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="dialog-container">
      <el-dialog title="修改失物招领" :visible.sync="dialogFormVisible">
        <el-form :model="lost">
          <el-form-item label="标题" :label-width="formLabelWidth">
            <el-input v-model="lost.title" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="lost.descrip" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="失物图片" style="padding-left: 53px">
            <el-upload
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
              :action="BASE_API+'/file/uploadInAdmin'"
              :data="UPLOADFILEBIZ"
              :headers="headers"
              name="avatar"
              class="avatar-uploader"
            >
              <img v-if="lost.picture" :src="lost.picture" width="100">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateData">保 存</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="paginationBar">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.current"
        :page-sizes="[4, 8, 12,16]"
        :page-size="this.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="total"
        style="width: 30% ;margin: 5px auto">
      </el-pagination>
    </div>

    <el-dialog title="新增信息" :visible.sync="addDialogFormVisible" @close="clearData">
      <el-form :model="lost">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="lost.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="lost.descrip" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="失物图片" style="padding-left: 53px">
          <el-upload
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :action="BASE_API+'/file/uploadInAdmin'"
            :data="UPLOADFILEBIZ"
            :headers="headers"
            name="avatar"
            class="avatar-uploader"
          >
            <img v-if="lost.picture" :src="lost.picture" width="100">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveData">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import lostAPI from "@/api/lost";
import {getToken} from "@/utils/auth";

export default {

  data() {
    return {
      BASE_API: 'http://localhost:8099',
      headers: {
        'token': getToken()
      },
      UPLOADFILEBIZ: {biz: 'lost_picture'},
      addDialogFormVisible: false,
      dialogFormVisible: false,
      isParent: false,
      lost: {isTop: 0},
      searchObj: {},
      current: 1,
      pageSize: 4,
      filterText: '',
      tableData: [],
      deleteBatchIds: [],
      multipleSelection: [],
      total: 0,
      topCategory: [],
      formLabelWidth: '120px',
      FOUND_STATUS: 1,
    }
  },
  created() {
    this.init()
  },

  methods: {
    handleFound(id) {
      this.$confirm('是否已被失主找回', '找回', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定找回'
      }).then(() => {
        lostAPI.changeStatusById(id, this.FOUND_STATUS).then(res => {
          this.$message.success("编号：" + id + "已被失主找回！")
          this.current = 1
          this.getLostList()
        })
      }).catch(action => {
          this.$message({
            type: "info",
            message: "操作取消"
          })
        }
      )

    },
    // 上传校验
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      if (res.code === 20000) {
        // console.log(res)
        this.lost.picture = res.data
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 （非0）')
      }
    },
    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败（http失败）')
    },
    handleRemove(file) {
      console.log(file)
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.lost.picture
      this.dialogVisible = true
    },
    clearData() {
      this.lost = {}
    },
    saveData() {
      lostAPI.saveLost(this.lost).then((res) => {
        this.$message({
          type: 'success',
          message: '新增成功！'
        })
        this.addDialogFormVisible = false
        this.init()
      })
    },
    showAddDialog() {
      this.addDialogFormVisible = true
    },
    handleUpdate(id) {
      this.dialogFormVisible = true
      lostAPI.getById(id).then(res => {
        this.lost = res.data
      })
    },
    // 根据id更新记录
    updateData() {
      lostAPI.updateById(this.lost.id, this.lost).then(response => {
        this.$message({
          type: 'success',
          message: '修改成功！'
        })
        this.dialogFormVisible = false
        this.init()
      })
    },
    handleDelete(index, row) {
      this.$confirm('是否要删除该条信息', '删除', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定删除'
      })
        .then(() => {
          lostAPI.deleteLost(row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
          })
          this.current = 1
          this.getLostList()
        })
        .catch(action => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
    },
    handleCurrentChange(val) {
      this.current = val
      this.getLostList()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getLostList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.deleteBatchIds = []
      this.multipleSelection.forEach(row => {
        this.deleteBatchIds.push(row.id)
      })
      console.log(this.deleteBatchIds)
    },
    handleBatchDelete(index, row) {
      if (this.deleteBatchIds.length === 0) {
        this.$message({
          type: 'warning',
          message: '未选择删除对象'
        })
        return
      } else {
        this.$confirm('是否要删除该条信息', '删除', {
          distinguishCancelAndClose: true,
          cancelButtonText: '取消',
          confirmButtonText: '确定删除'
        })
          .then(() => {
            lostAPI.deleteBatchLost(this.deleteBatchIds).then(() => {
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.current = 1
              this.init()
            })
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: '取消删除'
            })
          })
      }
    },
    changeBeginDate(val) {
      this.searchObj.beginTime = val
      this.getLostList()
    },
    changeEndDate(val) {
      this.searchObj.endTime = val
      this.getLostList()
    },
    init() {
      this.getLostList()
    },
    getLostList() {
      lostAPI.getLostPage(this.current, this.pageSize, this.searchObj).then(res => {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      )
    },
  }
}
</script>

<style scoped>
.demo-table-expand {
  margin-left: 75px;
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.avatar-uploader .avatar-uploader-icon {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-uploader img {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
